﻿using System;
using System.Collections.Generic;
using PureMVC.Interfaces;
using PureMVC.Patterns;
using SMS.Core.Model;

namespace SMS.Core.Controller.Commands
{
    /// <summary>
    /// Represents a stateless connection command to the
    /// PostgreSQL backend via an NpgsqlConnection
    /// </summary>
    class ConnectCommand : SimpleCommand, ICommand
    {
        #region ICommmand

        public new void Execute(INotification notification)
        {
            switch (notification.Name)
            {
                case ModelConstants.Connection.CONNECT:
                    // Build a connection string to pass the user input 
                    // which make up the connection string to the proxy.
                    //      IMPORTANT NOTE: This application listens to synchronous
                    //      notifications from the PostgreSQL backend.
                    var connParams = (List<string>)notification.Body;
                    var connString = String.Format(
                        @"Server={0};Port={1};User Id={3};Password={4};Database={2};SyncNotification=true",
                        connParams[0],
                        connParams[1],
                        connParams[2],
                        connParams[3],
                        connParams[4]);

                    // Register the connection proxy to initiate
                    // connection with the remote backend data.
                    var connProxy = new PersistentConnectionProxy(connString);
                    Facade.RegisterProxy(connProxy);

                    // Save this connection string as the application's connection string.
                    SMS.Core.Properties.Settings.Default.SMS_ConnectionString = connString;

                    // Make a connection attempt. 
                    // Send a CONNECTED notification if successful.
                    if (connProxy.OpenConnection())
                    {
                        Facade.RegisterProxy(new LoginProxy(connProxy.Data));
                    }
                    break;
            }
        }

        #endregion
    }
}
